﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Reflection;

namespace LyncServerExtension.PluginModel
{
    public sealed class AssemblyResolver: IDisposable
    {
        private List<string> paths = new List<string>();

        public List<string> Paths
        {
            get { return paths; }
        }

        public AssemblyResolver()
        {
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolve);
        }

        public void Dispose()
        {
            AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve;
        }

        private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            AssemblyName assemblyName = new AssemblyName(args.Name);
            
            foreach (var path in paths)
            {
                string assemblyPath = path;

                if (assemblyName.CultureInfo != null)
                    assemblyPath = Path.Combine(assemblyPath, assemblyName.CultureInfo.Name);

                assemblyPath = Path.Combine(assemblyPath, assemblyName.Name) + ".dll";
                try
                {
                    if (File.Exists(assemblyPath))
                        return Assembly.LoadFile(assemblyPath);
                }
                catch (Exception)
                {
                }
            }
            return null;
        }
    }
}